<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('商品单价统计')" />
    <th:block th:include="include :: bootstrap-select-css" />
</head>
<body class="gray-bg">
    <div class="container-div">
        <div class="row">
            <div class="col-sm-12 select-table">
                <div class="btn-group-sm" id="toolbar" role="group">
                    <!-- 导出按钮从这里移除 -->
                </div>
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>商品统计图表</h5>
                        <div class="ibox-tools">
                            <div class="btn-group" style="margin-right: 10px;">
                                <a class="btn btn-sm btn-success" onclick="exportExcel()" shiro:hasPermission="basedata:report:export">
                                    <i class="fa fa-download"></i> 导出
                                </a>
                                <button type="button" class="btn btn-sm btn-default active" id="chartTypeBar">
                                    <i class="fa fa-bar-chart"></i> 柱状图
                                </button>
                                <button type="button" class="btn btn-sm btn-default" id="chartTypeLine">
                                    <i class="fa fa-line-chart"></i> 折线图
                                </button>
                                <button type="button" class="btn btn-sm btn-default" id="chartTypePie">
                                    <i class="fa fa-pie-chart"></i> 饼状图
                                </button>
                            </div>
                            <div class="btn-group" style="margin-right: 10px;">
                                <button type="button" class="btn btn-sm btn-success active" id="showPriceChart">单价</button>
                                <button type="button" class="btn btn-sm btn-default" id="showVolumeChart">采购/销售量</button>
                            </div>
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                            <a class="close-link">
                                <i class="fa fa-times"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <!-- 添加明确的子标题，避免ECharts自动生成导致重叠 -->
                        <div class="text-center mb-10" style="margin-bottom: 15px;">
                            <span id="chartTitle" style="font-size: 20px; font-weight: bold;">商品单价统计</span>
                            <br/>
                            <span id="chartSubtitle" style="color: #666; font-size: 14px; margin-top: 5px; display: inline-block;">单价(元)</span>
                        </div>
                        <div class="echarts" id="combinedChart" style="height:700px;"></div>
                    </div>
                </div>
                
                <!-- 新增账户余额统计模块 -->
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>账户余额统计</h5>
                        <div class="ibox-tools">
                            <div class="btn-group" style="margin-right: 10px;">
                                <a class="btn btn-sm btn-success" onclick="exportAccountBalance()" shiro:hasPermission="basedata:report:export">
                                    <i class="fa fa-download"></i> 导出
                                </a>
                                <button type="button" class="btn btn-sm btn-default" id="refreshAccountData">
                                    <i class="fa fa-refresh"></i> 刷新数据
                                </button>
                            </div>
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                            <a class="close-link">
                                <i class="fa fa-times"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <!-- 账户余额表格 -->
                        <div class="table-responsive" style="margin-bottom: 20px;">
                            <table id="accountBalanceTable" class="table table-striped table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <th>账户名称</th>
                                        <th>账号</th>
                                        <th>银行名称</th>
                                        <th>当前余额</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- 数据由JavaScript填充 -->
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- 账户余额趋势图 -->
                        <div class="text-center mb-10" style="margin-bottom: 15px;">
                            <span style="font-size: 20px; font-weight: bold;">账户余额趋势图</span>
                            <br/>
                            <div class="btn-group" style="margin-top: 10px;">
                                <button type="button" class="btn btn-sm btn-default active" id="accountChartTypeLine">
                                    <i class="fa fa-line-chart"></i> 折线图
                                </button>
                                <button type="button" class="btn btn-sm btn-default" id="accountChartTypeArea">
                                    <i class="fa fa-area-chart"></i> 面积图
                                </button>
                                <select id="accountSelect" class="form-control input-sm" style="display:inline-block; width:auto; margin-left: 10px;">
                                    <option value="">所有账户</option>
                                </select>
                            </div>
                        </div>
                        <div class="echarts" id="balanceTrendChart" style="height:400px;"></div>
                    </div>
                </div>
                
                <!-- 财务利润报表 -->
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>财务利润报表</h5>
                        <div class="ibox-tools">
                            <div class="btn-group" style="margin-right: 10px;">
                                <a class="btn btn-sm btn-success" onclick="exportProfit()" shiro:hasPermission="fin:report:export">
                                    <i class="fa fa-download"></i> 导出
                                </a>
                                <button type="button" class="btn btn-sm btn-default active" id="profitChartBar">
                                    <i class="fa fa-bar-chart"></i> 柱状图
                                </button>
                                <button type="button" class="btn btn-sm btn-default" id="profitChartLine">
                                    <i class="fa fa-line-chart"></i> 折线图
                                </button>
                            </div>
                            <div class="btn-group" style="margin-right: 10px;">
                                <button type="button" class="btn btn-sm btn-success active" id="compareTypeMonth">环比</button>
                                <button type="button" class="btn btn-sm btn-default" id="compareTypeYear">同比</button>
                            </div>
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                            <a class="close-link">
                                <i class="fa fa-times"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <!-- 利润报表标题 -->
                        <div class="text-center mb-10" style="margin-bottom: 15px;">
                            <span id="profitChartTitle" style="font-size: 20px; font-weight: bold;">财务利润分析</span>
                            <br/>
                            <span id="profitChartSubtitle" style="color: #666; font-size: 14px; margin-top: 5px; display: inline-block;">收入/支出/利润(元)</span>
                            <br/>
                            <span id="compareTypeText" style="color: #3ba272; font-size: 14px; margin-top: 5px; display: inline-block;">【环比分析：与上月数据对比】</span>
                        </div>
                        <div class="echarts" id="profitChart" style="height:500px;"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: bootstrap-select-js" />
    <th:block th:include="include :: echarts-js" />
    
    <script type="text/javascript">
        var prefix = ctx + "basedata/report";
        var finPrefix = ctx + "fin/report";
        var combinedChart;
        var profitChart;
        var balanceTrendChart; // 账户余额趋势图实例
        var currentChartType = 'bar'; // 默认为柱状图
        var currentDataType = 'price'; // 默认显示单价图
        var profitChartType = 'bar'; // 利润图表类型
        var accountChartType = 'line'; // 账户余额图表类型
        var compareType = 'month'; // 默认环比
        var priceChartData = {}; // 存储单价图表数据
        var volumeChartData = {}; // 存储采购/销售量图表数据
        var profitChartData = {}; // 存储利润图表数据
        var accountBalanceData = []; // 存储账户余额数据
        var balanceTrendData = []; // 存储账户余额趋势数据
        
        $(function() {
            loadProductCountChart();
            loadProductVolumeChart();
            loadProfitChart();
            loadAccountBalanceData(); // 加载账户余额数据
            loadBalanceTrendData(); // 加载账户余额趋势数据
            
            // 添加切换图表类型按钮点击事件
            $("#chartTypeBar").click(function() {
                $(this).addClass("active");
                $("#chartTypeLine").removeClass("active");
                $("#chartTypePie").removeClass("active");
                currentChartType = 'bar';
                updateChart();
            });
            
            $("#chartTypeLine").click(function() {
                $(this).addClass("active");
                $("#chartTypeBar").removeClass("active");
                $("#chartTypePie").removeClass("active");
                currentChartType = 'line';
                updateChart();
            });
            
            $("#chartTypePie").click(function() {
                $(this).addClass("active");
                $("#chartTypeBar").removeClass("active");
                $("#chartTypeLine").removeClass("active");
                currentChartType = 'pie';
                updateChart();
            });
            
            // 添加切换数据类型按钮点击事件
            $("#showPriceChart").click(function() {
                $(this).addClass("active");
                $("#showVolumeChart").removeClass("active");
                currentDataType = 'price';
                updateChart();
            });
            
            $("#showVolumeChart").click(function() {
                $(this).addClass("active");
                $("#showPriceChart").removeClass("active");
                currentDataType = 'volume';
                updateChart();
            });
            
            // 添加切换利润图表类型按钮点击事件
            $("#profitChartBar").click(function() {
                $(this).addClass("active");
                $("#profitChartLine").removeClass("active");
                profitChartType = 'bar';
                updateProfitChart();
            });
            
            $("#profitChartLine").click(function() {
                $(this).addClass("active");
                $("#profitChartBar").removeClass("active");
                profitChartType = 'line';
                updateProfitChart();
            });
            
            // 添加切换比较类型按钮点击事件
            $("#compareTypeMonth").click(function() {
                if (!$(this).hasClass("active")) {
                    $(this).addClass("active");
                    $("#compareTypeYear").removeClass("active");
                    compareType = 'month';
                    
                    // 更新提示文本
                    $("#compareTypeText").text("【环比分析：与上月数据对比】").css("color", "#3ba272");
                    
                    // 显示加载中提示
                    var index = layer.msg('正在加载环比数据，请稍候...', {icon: 16, time: false, shade: 0.3});
                    
                    // 重新加载数据
                    setTimeout(function() {
                        loadProfitChart();
                        layer.close(index);
                    }, 300);
                }
            });
            
            $("#compareTypeYear").click(function() {
                if (!$(this).hasClass("active")) {
                    $(this).addClass("active");
                    $("#compareTypeMonth").removeClass("active");
                    compareType = 'year';
                    
                    // 更新提示文本
                    $("#compareTypeText").text("【同比分析：与去年同期数据对比】").css("color", "#ee6666");
                    
                    // 显示加载中提示
                    var index = layer.msg('正在加载同比数据，请稍候...', {icon: 16, time: false, shade: 0.3});
                    
                    // 重新加载数据
                    setTimeout(function() {
                        loadProfitChart();
                        layer.close(index);
                    }, 300);
                }
            });
            
            // 添加账户余额图表相关事件处理
            $("#accountChartTypeLine").click(function() {
                $(this).addClass("active");
                $("#accountChartTypeArea").removeClass("active");
                accountChartType = 'line';
                updateBalanceTrendChart();
            });
            
            $("#accountChartTypeArea").click(function() {
                $(this).addClass("active");
                $("#accountChartTypeLine").removeClass("active");
                accountChartType = 'area';
                updateBalanceTrendChart();
            });
            
            // 账户选择下拉框变更事件
            $("#accountSelect").change(function() {
                loadBalanceTrendData();
            });
            
            // 刷新账户数据按钮
            $("#refreshAccountData").click(function() {
                loadAccountBalanceData();
                loadBalanceTrendData();
            });
        });
        
        function loadProductCountChart() {
            $.ajax({
                type: "post",
                url: prefix + "/getProductCountData",
                dataType: "json",
                success: function(data) {
                    if (data.code == 0) {
                        processProductCountData(data.data);
                    } else {
                        $.modal.alertError(data.msg);
                    }
                }
            });
        }
        
        // 加载采购量和销售量数据
        function loadProductVolumeChart() {
            $.ajax({
                type: "post",
                url: prefix + "/getProductVolumeData",
                dataType: "json",
                success: function(data) {
                    if (data.code == 0) {
                        processProductVolumeData(data.data);
                    } else {
                        $.modal.alertError(data.msg);
                    }
                }
            });
        }
        
        function processProductCountData(data) {
            var productNames = [];
            var productPrices = [];
            
            // 处理数据
            if (data && data.length > 0) {
                $.each(data, function(index, item) {
                    if (item && item.name) {
                        productNames.push(item.name);
                        productPrices.push(item.value);
                    }
                });
            } else {
                // 如果没有数据，显示提示信息
                productNames = ["暂无数据"];
                productPrices = [0];
            }
            
            // 保存数据
            priceChartData = {
                productNames: productNames,
                values: productPrices
            };
            
            // 初始显示单价图
            updateChart();
        }
        
        // 处理采购量和销售量数据
        function processProductVolumeData(data) {
            var productNames = [];
            var purchaseData = [];
            var salesData = [];
            
            // 处理数据
            if (data && data.length > 0) {
                $.each(data, function(index, item) {
                    if (item && item.name) {
                        productNames.push(item.name);
                        purchaseData.push(item.purchase);
                        salesData.push(item.sales);
                    }
                });
            } else {
                // 如果没有数据，显示提示信息
                productNames = ["暂无数据"];
                purchaseData = [0];
                salesData = [0];
            }
            
            // 保存数据
            volumeChartData = {
                productNames: productNames,
                purchaseData: purchaseData,
                salesData: salesData
            };
        }
        
        // 更新图表
        function updateChart() {
            // 初始化ECharts实例（如果尚未初始化）
            if (!combinedChart) {
                combinedChart = echarts.init(document.getElementById('combinedChart'));
                
                // 响应式图表
                window.addEventListener('resize', function() {
                    combinedChart.resize();
                });
            }
            
            var option;
            
            // 根据当前数据类型选择不同的图表配置
            if (currentDataType === 'price') {
                $("#chartTitle").text("商品单价统计");
                $("#chartSubtitle").text("单价(元)");
                option = getPriceChartOption();
            } else {
                $("#chartTitle").text("采购量和销售量对比");
                $("#chartSubtitle").text("数量(件)");
                option = getVolumeChartOption();
            }
            
            // 使用配置项和数据显示图表
            combinedChart.setOption(option, true);
        }
        
        // 获取单价图表配置
        function getPriceChartOption() {
            // 如果是饼图，使用不同的配置
            if (currentChartType === 'pie') {
                return getPricePieOption();
            }
            
            var option = {
                backgroundColor: '#fff',
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: currentChartType === 'bar' ? 'shadow' : 'line'
                    },
                    formatter: function(params) {
                        return params[0].name + '<br/>' + 
                              '单价: <b>¥' + params[0].value.toFixed(2) + '</b>';
                    },
                    textStyle: {
                        fontSize: 14
                    }
                },
                legend: {
                    data: ['单价'],
                    top: 10,
                    right: '10%',
                    textStyle: {
                        fontSize: 12
                    }
                },
                grid: {
                    left: '10%',
                    right: '10%',
                    bottom: '30%',
                    top: '15%'
                },
                xAxis: {
                    type: 'category',
                    data: priceChartData.productNames || [],
                    name: '商品名称',
                    nameLocation: 'middle',
                    nameGap: 90,
                    nameTextStyle: {
                        fontSize: 14,
                        fontWeight: 'bold',
                        padding: [30, 0, 0, 0],
                        color: '#333'
                    },
                    axisLabel: {
                        show: true,
                        interval: 0,
                        rotate: 45,
                        fontSize: 13,
                        margin: 20,
                        align: 'right',
                        padding: [5, 0, 0, 0],
                        textStyle: {
                            color: '#333'
                        },
                        formatter: function(value) {
                            return value;
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: '#999'
                        }
                    },
                    axisTick: {
                        alignWithLabel: true,
                        lineStyle: {
                            color: '#999'
                        }
                    },
                    splitLine: {
                        show: false
                    },
                    boundaryGap: currentChartType === 'bar' ? true : false
                },
                yAxis: {
                    type: 'value',
                    name: '单价(元)',
                    nameLocation: 'middle',
                    nameGap: 70,
                    nameTextStyle: {
                        fontSize: 14,
                        fontWeight: 'bold',
                        padding: [0, 0, 30, 0],
                        color: '#333'
                    },
                    axisLabel: {
                        formatter: '¥{value}',
                        fontSize: 13,
                        color: '#333'
                    },
                    splitLine: {
                        lineStyle: {
                            type: 'dashed',
                            color: '#DDD'
                        }
                    }
                },
                series: [
                    {
                        name: '单价',
                        type: currentChartType,
                        data: priceChartData.values || [],
                        barWidth: currentChartType === 'bar' ? '35%' : undefined,
                        barGap: '30%',
                        itemStyle: {
                            normal: {
                                color: function(params) {
                                    // 使用更加柔和的配色方案
                                    var colorList = [
                                        '#5470c6', '#91cc75', '#fac858', '#ee6666', 
                                        '#73c0de', '#3ba272', '#fc8452', '#9a60b4',
                                        '#ea7ccc', '#55a1ea', '#71c0a7'
                                    ];
                                    return colorList[params.dataIndex % colorList.length];
                                },
                                barBorderRadius: currentChartType === 'bar' ? [4, 4, 0, 0] : 0
                            }
                        },
                        label: {
                            show: currentChartType === 'bar',
                            position: 'top',
                            distance: 10,
                            fontSize: 14,
                            fontWeight: 'bold',
                            formatter: '¥{c}',
                            textStyle: {
                                color: '#333'
                            }
                        },
                        smooth: currentChartType === 'line' ? true : false,
                        symbol: currentChartType === 'line' ? 'circle' : 'none',
                        symbolSize: currentChartType === 'line' ? 8 : 4,
                        lineStyle: currentChartType === 'line' ? {
                            width: 3
                        } : undefined,
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };
            
            return option;
        }
        
        // 单价饼图配置
        function getPricePieOption() {
            var data = [];
            var colorList = [
                '#5470c6', '#91cc75', '#fac858', '#ee6666', 
                '#73c0de', '#3ba272', '#fc8452', '#9a60b4',
                '#ea7ccc', '#55a1ea', '#71c0a7'
            ];
            
            // 处理数据
            if (priceChartData.productNames && priceChartData.values) {
                for (var i = 0; i < priceChartData.productNames.length; i++) {
                    data.push({
                        name: priceChartData.productNames[i],
                        value: priceChartData.values[i]
                    });
                }
            }
            
            var option = {
                backgroundColor: '#fff',
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        return params.name + '<br/>单价: <b>¥' + params.value.toFixed(2) + '</b> (' + params.percent.toFixed(1) + '%)';
                    }
                },
                legend: {
                    type: 'scroll',
                    orient: 'vertical',
                    right: 10,
                    top: 20,
                    bottom: 20,
                    textStyle: {
                        fontSize: 12
                    }
                },
                series: [
                    {
                        name: '单价',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        center: ['40%', '50%'],
                        avoidLabelOverlap: true,
                        itemStyle: {
                            borderRadius: 8,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: true,
                            formatter: '{b}: ¥{c}'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '14',
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: true
                        },
                        data: data
                    }
                ]
            };
            
            return option;
        }
        
        // 获取采购量和销售量图表配置
        function getVolumeChartOption() {
            // 如果是饼图，使用不同的配置
            if (currentChartType === 'pie') {
                return getVolumePieOption();
            }
            
            var option = {
                backgroundColor: '#fff',
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: currentChartType === 'bar' ? 'shadow' : 'line'
                    },
                    formatter: function(params) {
                        var result = params[0].name + '<br/>';
                        params.forEach(function(param) {
                            result += param.seriesName + ': ' + param.value + ' 件<br/>';
                        });
                        return result;
                    },
                    textStyle: {
                        fontSize: 14
                    }
                },
                legend: {
                    data: ['采购量', '销售量'],
                    top: 10,
                    right: '10%',
                    textStyle: {
                        fontSize: 12
                    }
                },
                grid: {
                    left: '10%',
                    right: '10%',
                    bottom: '30%',
                    top: '15%'
                },
                xAxis: {
                    type: 'category',
                    data: volumeChartData.productNames || [],
                    name: '商品名称',
                    nameLocation: 'middle',
                    nameGap: 90,
                    nameTextStyle: {
                        fontSize: 14,
                        fontWeight: 'bold',
                        padding: [30, 0, 0, 0],
                        color: '#333'
                    },
                    axisLabel: {
                        show: true,
                        interval: 0,
                        rotate: 45,
                        fontSize: 13,
                        margin: 20,
                        align: 'right',
                        padding: [5, 0, 0, 0],
                        textStyle: {
                            color: '#333'
                        },
                        formatter: function(value) {
                            return value;
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: '#999'
                        }
                    },
                    axisTick: {
                        alignWithLabel: true,
                        lineStyle: {
                            color: '#999'
                        }
                    },
                    splitLine: {
                        show: false
                    },
                    boundaryGap: currentChartType === 'bar' ? true : false
                },
                yAxis: {
                    type: 'value',
                    name: '数量(件)',
                    nameLocation: 'middle',
                    nameGap: 70,
                    nameTextStyle: {
                        fontSize: 14,
                        fontWeight: 'bold',
                        padding: [0, 0, 30, 0],
                        color: '#333'
                    },
                    axisLabel: {
                        formatter: '{value}',
                        fontSize: 13,
                        color: '#333'
                    },
                    splitLine: {
                        lineStyle: {
                            type: 'dashed',
                            color: '#DDD'
                        }
                    }
                },
                series: [
                    {
                        name: '采购量',
                        type: currentChartType,
                        data: volumeChartData.purchaseData || [],
                        barWidth: currentChartType === 'bar' ? '30%' : undefined,
                        itemStyle: {
                            normal: {
                                color: '#5470c6',
                                barBorderRadius: currentChartType === 'bar' ? [4, 4, 0, 0] : 0
                            }
                        },
                        label: {
                            show: currentChartType === 'bar',
                            position: 'top',
                            distance: 10,
                            fontSize: 14,
                            fontWeight: 'bold',
                            formatter: '{c}',
                            textStyle: {
                                color: '#333'
                            }
                        },
                        smooth: currentChartType === 'line' ? true : false,
                        symbol: currentChartType === 'line' ? 'circle' : 'none',
                        symbolSize: currentChartType === 'line' ? 8 : 4,
                        lineStyle: currentChartType === 'line' ? {
                            width: 3
                        } : undefined
                    },
                    {
                        name: '销售量',
                        type: currentChartType,
                        data: volumeChartData.salesData || [],
                        barWidth: currentChartType === 'bar' ? '30%' : undefined,
                        itemStyle: {
                            normal: {
                                color: '#91cc75',
                                barBorderRadius: currentChartType === 'bar' ? [4, 4, 0, 0] : 0
                            }
                        },
                        label: {
                            show: currentChartType === 'bar',
                            position: 'top',
                            distance: 10,
                            fontSize: 14,
                            fontWeight: 'bold',
                            formatter: '{c}',
                            textStyle: {
                                color: '#333'
                            }
                        },
                        smooth: currentChartType === 'line' ? true : false,
                        symbol: currentChartType === 'line' ? 'circle' : 'none',
                        symbolSize: currentChartType === 'line' ? 8 : 4,
                        lineStyle: currentChartType === 'line' ? {
                            width: 3
                        } : undefined
                    }
                ]
            };
            
            return option;
        }
        
        // 采购量和销售量饼图配置
        function getVolumePieOption() {
            var purchaseData = [];
            var salesData = [];
            var colorList = [
                '#5470c6', '#91cc75', '#fac858', '#ee6666', 
                '#73c0de', '#3ba272', '#fc8452', '#9a60b4',
                '#ea7ccc', '#55a1ea', '#71c0a7'
            ];
            
            // 处理数据
            if (volumeChartData.productNames && volumeChartData.purchaseData && volumeChartData.salesData) {
                for (var i = 0; i < volumeChartData.productNames.length; i++) {
                    purchaseData.push({
                        name: volumeChartData.productNames[i],
                        value: volumeChartData.purchaseData[i]
                    });
                    salesData.push({
                        name: volumeChartData.productNames[i],
                        value: volumeChartData.salesData[i]
                    });
                }
            }
            
            var option = {
                backgroundColor: '#fff',
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        return params.name + '<br/>' + params.seriesName + ': <b>' + params.value + '</b> 件 (' + params.percent.toFixed(1) + '%)';
                    }
                },
                legend: {
                    type: 'scroll',
                    orient: 'vertical',
                    right: 10,
                    top: 20,
                    bottom: 20,
                    textStyle: {
                        fontSize: 12
                    }
                },
                series: [
                    {
                        name: '采购量',
                        type: 'pie',
                        radius: ['20%', '40%'],
                        center: ['30%', '50%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 8,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '14',
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: purchaseData
                    },
                    {
                        name: '销售量',
                        type: 'pie',
                        radius: ['20%', '40%'],
                        center: ['70%', '50%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 8,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '14',
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: salesData
                    }
                ]
            };
            
            return option;
        }
        
        // 更新利润图表
        function updateProfitChart() {
            // 显示加载提示
            var loadingIndex = layer.msg('正在更新图表，请稍候...', {icon: 16, time: false, shade: 0.3});
            
            // 获取当前图表实例
            if (!profitChart) {
                profitChart = echarts.init(document.getElementById('profitChart'));
            }
            
            // 更新图表类型
            var currentOption = profitChart.getOption();
            if (currentOption && currentOption.series && currentOption.series.length > 0) {
                for (var i = 0; i < currentOption.series.length; i++) {
                    currentOption.series[i].type = profitChartType;
                }
                
                // 应用新配置
                profitChart.setOption(currentOption, true);
                layer.close(loadingIndex);
                
                // 显示提示
                layer.msg('图表类型已更新为' + (profitChartType === 'bar' ? '柱状图' : '折线图'), {
                    icon: 1,
                    time: 1000
                });
            } else {
                // 如果还没有图表数据，则重新加载
                layer.close(loadingIndex);
                loadProfitChart();
            }
        }
        
        function loadProfitChart() {
            var params = {
                compareType: compareType // 传递比较类型参数
            };
            $.ajax({
                type: "GET",
                url: ctx + "fin/profit/data",
                data: params,
                success: function(res) {
                    if (res.code == 0) {
                        // 更新标题
                        var titleText = compareType === 'month' ? 
                            "财务利润环比分析" : 
                            "财务利润同比分析";
                        
                        // 初始化profitChart
                        if (!profitChart) {
                            profitChart = echarts.init(document.getElementById('profitChart'));
                        }
                        
                        var option = {
                            title: {
                                text: titleText,
                                left: 'center',
                                show: false
                            },
                            tooltip: {
                                trigger: 'axis',
                                axisPointer: {
                                    type: 'shadow'
                                },
                                formatter: function(params) {
                                    var result = params[0].name + '<br/>';
                                    for (var i = 0; i < params.length; i++) {
                                        var marker = '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:' + params[i].color + '"></span>';
                                        result += marker + params[i].seriesName + ': ' + params[i].value + '元<br/>';
                                    }
                                    return result;
                                }
                            },
                            legend: {
                                data: ['收入', '支出', '利润'],
                                top: 'top'
                            },
                            grid: {
                                left: '3%',
                                right: '4%',
                                bottom: '3%',
                                containLabel: true
                            },
                            xAxis: {
                                type: 'category',
                                data: res.data.categories || [],
                                axisLabel: {
                                    interval: 0,
                                    rotate: 45
                                }
                            },
                            yAxis: {
                                type: 'value',
                                name: '金额（元）'
                            },
                            series: [
                                {
                                    name: '收入',
                                    type: profitChartType,
                                    barWidth: '40%',
                                    data: res.data.income || [],
                                    itemStyle: {
                                        color: '#3ba272'
                                    }
                                },
                                {
                                    name: '支出',
                                    type: profitChartType,
                                    barWidth: '40%',
                                    data: res.data.expense || [],
                                    itemStyle: {
                                        color: '#ee6666'
                                    }
                                },
                                {
                                    name: '利润',
                                    type: profitChartType,
                                    barWidth: '40%',
                                    data: res.data.profit || [],
                                    itemStyle: {
                                        color: '#5470c6'
                                    }
                                }
                            ]
                        };
                        profitChart.setOption(option);
                        window.addEventListener('resize', function() {
                            profitChart.resize();
                        });
                        
                        // 显示图表加载完成的通知
                        layer.msg(compareType === 'month' ? '环比数据已更新' : '同比数据已更新', {
                            icon: 1,
                            time: 1000
                        });
                    } else {
                        $.modal.alertError(res.msg);
                    }
                },
                error: function() {
                    $.modal.alertError("加载数据失败");
                }
            });
        }
        
        // 加载账户余额数据
        function loadAccountBalanceData() {
            $.ajax({
                type: "post",
                url: finPrefix + "/getAccountBalanceData",
                dataType: "json",
                success: function(data) {
                    if (data.code == 0) {
                        processAccountBalanceData(data.data);
                    } else {
                        $.modal.alertError(data.msg);
                    }
                }
            });
        }
        
        // 处理账户余额数据
        function processAccountBalanceData(data) {
            accountBalanceData = data;
            
            // 清空表格
            $("#accountBalanceTable tbody").empty();
            
            // 清空账户下拉框
            $("#accountSelect").empty();
            $("#accountSelect").append('<option value="">所有账户</option>');
            
            // 处理数据
            if (data && data.length > 0) {
                $.each(data, function(index, item) {
                    if (item) {
                        // 添加到表格
                        if (item.accountId != 0) { // 不显示总计行
                            var row = '<tr>' +
                                '<td>' + item.accountName + '</td>' +
                                '<td>' + (item.accountNo || '') + '</td>' +
                                '<td>' + (item.bankName || '') + '</td>' +
                                '<td class="text-right">' + formatMoney(item.balance) + '</td>' +
                                '</tr>';
                            $("#accountBalanceTable tbody").append(row);
                            
                            // 添加到账户下拉框
                            $("#accountSelect").append('<option value="' + item.accountId + '">' + item.accountName + '</option>');
                        } else {
                            // 总计行特殊样式
                            var totalRow = '<tr class="active">' +
                                '<td><strong>' + item.accountName + '</strong></td>' +
                                '<td></td>' +
                                '<td></td>' +
                                '<td class="text-right"><strong>' + formatMoney(item.balance) + '</strong></td>' +
                                '</tr>';
                            $("#accountBalanceTable tbody").append(totalRow);
                        }
                    }
                });
            } else {
                // 如果没有数据，显示提示信息
                $("#accountBalanceTable tbody").append('<tr><td colspan="4" class="text-center">暂无数据</td></tr>');
            }
        }
        
        // 加载余额趋势数据
        function loadBalanceTrendData() {
            var accountId = $("#accountSelect").val();
            
            $.ajax({
                type: "post",
                url: finPrefix + "/getAccountBalanceTrendData",
                data: {
                    accountId: accountId || ""
                },
                dataType: "json",
                success: function(data) {
                    if (data.code == 0) {
                        processBalanceTrendData(data.data);
                    } else {
                        $.modal.alertError(data.msg);
                    }
                }
            });
        }
        
        // 处理余额趋势数据
        function processBalanceTrendData(data) {
            balanceTrendData = data;
            updateBalanceTrendChart();
        }
        
        // 更新余额趋势图表
        function updateBalanceTrendChart() {
            // 初始化ECharts实例（如果尚未初始化）
            if (!balanceTrendChart) {
                balanceTrendChart = echarts.init(document.getElementById('balanceTrendChart'));
                
                // 响应式图表
                window.addEventListener('resize', function() {
                    if (balanceTrendChart) {
                        balanceTrendChart.resize();
                    }
                });
            }
            
            var option = getBalanceTrendChartOption();
            
            // 使用配置项和数据显示图表
            balanceTrendChart.setOption(option, true);
        }
        
        // 获取余额趋势图配置
        function getBalanceTrendChartOption() {
            // 按账户ID分组数据
            var accountGroups = {};
            var dateSet = new Set();
            
            balanceTrendData.forEach(function(item) {
                // 记录所有出现的日期
                dateSet.add(item.recordDate);
                
                // 按账户ID分组
                if (!accountGroups[item.accountId]) {
                    accountGroups[item.accountId] = {
                        name: item.accountName,
                        data: {}
                    };
                }
                
                // 保存每个日期的余额
                accountGroups[item.accountId].data[item.recordDate] = item.balance;
            });
            
            // 转换日期集合为排序的数组
            var dateList = Array.from(dateSet).sort();
            
            // 构建系列数据
            var series = [];
            var colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4'];
            var colorIndex = 0;
            
            for (var accountId in accountGroups) {
                var accountData = accountGroups[accountId];
                var seriesData = [];
                
                // 对每个日期，获取该账户的余额
                dateList.forEach(function(date) {
                    seriesData.push(accountData.data[date] || 0);
                });
                
                // 创建系列
                var seriesItem = {
                    name: accountData.name,
                    type: 'line', // 使用线图
                    data: seriesData,
                    symbol: 'circle',
                    symbolSize: 6,
                    itemStyle: {
                        color: colors[colorIndex % colors.length]
                    },
                    lineStyle: {
                        width: 2
                    },
                    smooth: true
                };
                
                // 如果是面积图，添加区域样式
                if (accountChartType === 'area') {
                    seriesItem.areaStyle = {
                        opacity: 0.3
                    };
                }
                
                series.push(seriesItem);
                colorIndex++;
            }
            
            var option = {
                backgroundColor: '#fff',
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    },
                    formatter: function(params) {
                        var result = params[0].axisValue + '<br/>';
                        params.forEach(function(param) {
                            var color = param.color;
                            var value = formatMoney(param.value);
                            result += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:' + color + '"></span>';
                            result += param.seriesName + ': ' + value + '<br/>';
                        });
                        return result;
                    }
                },
                legend: {
                    data: Object.values(accountGroups).map(function(account) {
                        return account.name;
                    }),
                    top: 10,
                    right: '10%',
                    textStyle: {
                        fontSize: 12
                    }
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '10%',
                    top: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: dateList,
                    name: '日期',
                    nameLocation: 'middle',
                    nameGap: 40,
                    nameTextStyle: {
                        fontSize: 14,
                        fontWeight: 'bold',
                        padding: [15, 0, 0, 0],
                        color: '#333'
                    },
                    axisLabel: {
                        rotate: 45,
                        interval: Math.floor(dateList.length / 12), // 自动计算间隔以避免标签重叠
                        textStyle: {
                            fontSize: 12
                        }
                    },
                    boundaryGap: false
                },
                yAxis: {
                    type: 'value',
                    name: '余额(元)',
                    nameLocation: 'middle',
                    nameGap: 50,
                    nameTextStyle: {
                        fontSize: 14,
                        fontWeight: 'bold',
                        padding: [0, 0, 20, 0],
                        color: '#333'
                    },
                    axisLabel: {
                        formatter: function(value) {
                            return formatMoney(value, 0);
                        },
                        fontSize: 12
                    },
                    splitLine: {
                        lineStyle: {
                            type: 'dashed',
                            color: '#DDD'
                        }
                    }
                },
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: 100
                    },
                    {
                        start: 0,
                        end: 100
                    }
                ],
                series: series
            };
            
            return option;
        }
        
        // 格式化货币数字
        function formatMoney(value, decimals) {
            if (value === undefined || value === null) {
                return '¥0.00';
            }
            
            decimals = decimals !== undefined ? decimals : 2;
            value = parseFloat(value);
            return '¥' + value.toFixed(decimals).replace(/\d(?=(\d{3})+\.)/g, '$&,');
        }
        
        // 切换图表类型
        function toggleChartType() {
            // 切换图表类型
            currentChartType = currentChartType === 'bar' ? 'line' : 'bar';
            
            // 更新按钮图标和文本
            if (currentChartType === 'bar') {
                $("#toggleChartType").html('<i class="fa fa-line-chart"></i> 切换为折线图');
            } else {
                $("#toggleChartType").html('<i class="fa fa-bar-chart"></i> 切换为柱状图');
            }
            
            // 重新渲染图表
            updateChart();
        }
        
        // 搜索按钮点击事件
        function searchData() {
            // 直接加载数据，不需要处理时间参数
            loadProductCountChart();
            loadProductVolumeChart();
            loadProfitChart();
            loadBalanceTrendData();
        }
        
        // 重置按钮点击事件
        function resetForm() {
            // 直接加载数据，不需要重置时间输入框
            loadProductCountChart();
            loadProductVolumeChart();
            loadProfitChart();
            loadBalanceTrendData();
        }
        
        // 导出Excel
        function exportExcel() {
            $.modal.confirm("确定导出所有商品统计数据吗？", function() {
                // 构建参数
                var params = {};
                
                // 使用若依框架的导出功能
                $.modal.loading("正在导出数据，请稍候...");
                
                // 根据当前显示的数据类型决定导出内容
                var exportUrl = "";
                if (currentDataType === 'price') {
                    exportUrl = prefix + "/exportProductPrice";
                } else {
                    exportUrl = prefix + "/exportProductVolume";
                }
                
                // 使用表单提交方式导出
                $.post(exportUrl, params, function(result) {
                    if (result.code == web_status.SUCCESS) {
                        window.location.href = ctx + "common/download?fileName=" + encodeURI(result.msg) + "&delete=" + true;
                        // 设置定时器，确保下载开始后关闭加载提示
                        setTimeout(function() {
                            $.modal.closeLoading();
                            $.modal.msgSuccess("导出成功");
                        }, 1000);
                    } else {
                        $.modal.closeLoading();
                        $.modal.alertError(result.msg);
                    }
                }).fail(function() {
                    $.modal.closeLoading();
                    $.modal.alertError("导出失败，请联系管理员");
                });
            });
        }
        
        // 导出账户余额数据
        function exportAccountBalance() {
            $.modal.confirm("确定导出账户余额统计数据吗？", function() {
                var accountId = $("#accountSelect").val();
                
                // 构建参数
                var params = {
                    accountId: accountId || ''
                };
                
                // 使用若依框架的导出功能
                $.modal.loading("正在导出账户余额数据，请稍候...");
                
                // 导出账户余额数据
                var exportUrl = finPrefix + "/exportAccountBalance";
                
                // 使用表单提交方式导出
                $.post(exportUrl, params, function(result) {
                    if (result.code == web_status.SUCCESS) {
                        window.location.href = ctx + "common/download?fileName=" + encodeURI(result.msg) + "&delete=" + true;
                        // 设置定时器，确保下载开始后关闭加载提示
                        setTimeout(function() {
                            $.modal.closeLoading();
                            $.modal.msgSuccess("导出成功");
                        }, 1000);
                    } else {
                        $.modal.closeLoading();
                        $.modal.alertError(result.msg);
                    }
                }).fail(function() {
                    $.modal.closeLoading();
                    $.modal.alertError("导出失败，请联系管理员");
                });
            });
        }
        
        // 导出财务利润报表数据
        function exportProfit() {
            $.modal.confirm("确定导出财务利润报表数据吗？", function() {
                // 构建参数
                var params = {};
                
                // 使用若依框架的导出功能
                $.modal.loading("正在导出财务利润报表数据，请稍候...");
                
                // 导出财务利润报表数据
                var exportUrl = finPrefix + "/exportProfitReport";
                
                // 使用表单提交方式导出
                $.post(exportUrl, params, function(result) {
                    if (result.code == web_status.SUCCESS) {
                        window.location.href = ctx + "common/download?fileName=" + encodeURI(result.msg) + "&delete=" + true;
                        // 设置定时器，确保下载开始后关闭加载提示
                        setTimeout(function() {
                            $.modal.closeLoading();
                            $.modal.msgSuccess("导出成功");
                        }, 1000);
                    } else {
                        $.modal.closeLoading();
                        $.modal.alertError(result.msg);
                    }
                }).fail(function() {
                    $.modal.closeLoading();
                    $.modal.alertError("导出失败，请联系管理员");
                });
            });
        }
    </script>
</body>
</html> 